﻿function FacebookBoardService(boardID, dialogID, tableID) {
    this.boardID = boardID;
    var _putDialog = $('#put-' + dialogID);
    var _parseMethod = this.parsePosts;
    _putDialog.dialog({
        autoOpen: false,
        height: 350,
        width: 500,
        modal: true,
        title: 'Load Topic Posts',
        open: function (event, ui) {
            var t = $('#PageSource');
            t.focus();
            t.val('');
        },
        buttons: {
            'Parse': function () {
                var topicID = parseInt($('#TopicID').val());
                var obj = _parseMethod($('#PageSource').val(), boardID, topicID);
                if (obj.Posts && obj.Posts.length > 0)
                    PageBus.publish('table.put.' + tableID, obj);
            },
            'Close': function () {
                _putDialog.dialog("close");
            }
        }
    });
    this.putDialog = _putDialog;
    var _dialog = $('#' + dialogID);
    var _boardID = this.boardID;
    _dialog.dialog({
        autoOpen: false,
        width: 500,
        height: 600,
        modal: true,
        title: 'Topic Details',
        open: function () {
            $('.Source').autocomplete({ source: allSources });
            iconify();
        },
        buttons: {
            'Save': function () {
                var obj = {};
                obj.ID = parseInt($('#postID').val());
                obj.TopicID = parseInt($('#topicID').val());
                obj.BoardID = _boardID;
                obj.WordCount = parseInt($('#WordCount').val());
                obj.Links = [];
                var sections = $(".postLink");
                for (var i = 0; i < sections.length; i++) {
                    var section = $(sections[i]);
                    var id = parseInt(section.attr('data-id'));
                    var link = {};
                    link.ID = id;
                    link.PostID = obj.ID;
                    link.TopicID = obj.TopicID;
                    link.BoardID = obj.BoardID;
                    link.ActualUrl = $('#ActualUrl-' + id).val();
                    link.Source = $('#Source-' + id).val();

                    if (jQuery.inArray(link.Source, allSources) < 0)
                        allSources.push(link.Source);
                    link.Broadcast = $("input[name='Broadcast-" + id + "']:checked").val();
                    link.Citation = $("input[name='Citation-" + id + "']:checked").val();
                    link.Level2 = $("input[name='Level2-" + id + "']:checked").val();
                    link.Old = $("input[name='Old-" + id + "']:checked").val();
                    obj.Links.push(link);
                }
                window.PageBus.publish('table.save.' + tableID, obj);
            },
            'Close': function () {
                _dialog.dialog("close");
            }
        }
    });
    this.dialog = _dialog;
}
FacebookBoardService.prototype.dialog = null;
FacebookBoardService.prototype.putDialog = null;
FacebookBoardService.prototype.boardID = null;
FacebookBoardService.prototype.edit = function (values) {
    var _dialog = this.dialog;
    function myEditCallback(result) {
        _dialog.html(result);
        _dialog.dialog("open");
    }
    Service.get("/Facebook/Board/" + this.boardID + "/" + values[0], null, myEditCallback, "html");
};
FacebookBoardService.prototype.save = function (obj, callback) {
    var _dialog = this.dialog;
    function myCallback(result) {
        _dialog.dialog("close");
        callback(result);
    }
    Service.postJson("/Facebook/SavePostLinks", obj, myCallback);
};
//FacebookBoardService.prototype.openput = function (values) {
//    var url = "http://www.facebook.com/topic.php?uid=" + this.boardID + "&topic=" + values[0];
//    $('#TopicID').val(values[0]);
//    this.putDialog.dialog("open");
//};
FacebookBoardService.prototype.put = function (obj, callback) {
    var _dialog = this.putDialog;
    function myCallback(result) {
        _dialog.dialog("close");
        callback(result);
    }
    Service.postJson("/Facebook/LoadTopic", obj, myCallback);
}
FacebookBoardService.prototype.parsePosts = function (content, boardID, topicID) {
    if (!content || content.length == 0) {
        alert("No source found!");
        return;
    }
    var topic = {};
    topic.BoardID = boardID;
    topic.ID = topicID;
    topic.Posts = [];
    var topicTotalRegex = /<div class="summary">.+?\s(\d+)\spost/i;
    var topicTotalMatch = topicTotalRegex.exec(content);
    if (topicTotalMatch) {
        topic.TotalPosts = parseInt(topicTotalMatch[1]);
    } else {
        topic.TotalPosts = 1;
    }
    var start = content.indexOf('<div class="DiscussionThread">') - 1;
    if (start < 0) return;
    var end = content.indexOf('<div class="pagerpro_container">', start);
    var div = "";
    if (end < 0)
        end = content.indexOf('<div id="editor"', start);
    if (end < start)
        div = content.substring(start);
    else
        div = content.substring(start, end);
    var deletedID = 0;
    var segments = div.split(/<li class="\w\w\w\s/g);
    var users = [];
    for (var segmentsIndex = 1; segmentsIndex < segments.length; segmentsIndex++) {
        var post;
        var match = segments[segmentsIndex].match(/id="post(\d+?)">.+?actorDescription".+?>(.+?)<\/div>\s*<span class="messageBody".+?>(.+?)<\/span><?\/h6>.+?<abbr.+?data-date="(.+?)"/);
        if (match) {
            post = {};
            post.ID = parseInt(match[1]);
            post.Poster = match[2].replace(/<[^>]+>/g, '');
            post.Text = match[3];
            post.CreatedDateString = match[4];
            if (users.indexOf(post.Poster) < 0)
                users.push(post.Poster);
        } else {
            match = div.match(/Post Deleted<\/h6>.+?<abbr.+?data-date="(.+?)"/);
            if (match) {
                post = {};
                post.ID = ++deletedID;
                post.Poster = '';
                post.Text = 'Post Deleted';
                post.CreatedDateString = match[1];
            }
        }
        if (post) {
            post.BoardID = boardID;
            post.TopicID = topicID;
            post.Genre = '';
            post.Subject = '';
            topic.Posts.push(post);
        }
    }
    topic.UniqueUsers = users.length;
    return topic;
};